<template>
  <div class="app-container">
    <el-card shadow="never" >
      <template #header>
        <div class="header-container">
          <el-page-header @back="goBack" :content="'货件详情 - ' + form.shipmentConfirmationId">
            <template #content>
              <span>货件详情 - {{ form.shipmentConfirmationId }}</span>
            </template>
          </el-page-header>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="货件编码">{{ form.shipmentConfirmationId }}</el-descriptions-item>
        <el-descriptions-item label="FBA地址">{{ form.warehouseId }}</el-descriptions-item>
        <el-descriptions-item label="归属工厂">{{ form.factory }}</el-descriptions-item>
        <el-descriptions-item label="店铺名称">{{ form.shopName }}</el-descriptions-item>
        <el-descriptions-item label="发货材料及编号">{{ form.materialAndNumber }}</el-descriptions-item>
        <el-descriptions-item label="货件追踪编号">{{ form.trackingNumber }}</el-descriptions-item>
        <el-descriptions-item label="员工姓名">{{ form.employeeName }}</el-descriptions-item>
        <el-descriptions-item label="头程方式">{{ form.firstJourney }}</el-descriptions-item>
        <el-descriptions-item label="送货地址">{{ form.shippingAddress }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ parseTime(form.orderTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ parseTime(form.shipmentsTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="statusOptions" :value="form.status" />
        </el-descriptions-item>
      </el-descriptions>


      <!-- 打包下发工厂按钮 -->
      <div style="margin-top: 20px; margin-bottom: 20px;">
        <el-button type="primary" size="small" style="float: right;" @click="showDialog = true">打包下发工厂</el-button>
        <div style="clear: both;"></div>
      </div>

      <!-- 打包下发工厂弹出对话框 -->
      <el-dialog v-model="showDialog" title="打包下发工厂" width="50%">
        <el-steps :active="activeStep" finish-status="success" align-center>
          <el-step title="选择下发工厂"></el-step>
          <el-step title="选择下发账号"></el-step>
          <el-step title="确认下发"></el-step>
        </el-steps>

        <div v-if="activeStep === 0">
          <el-select v-model="selectedFactory" placeholder="请选择下发工厂">
            <el-option v-for="factory in factoryOptions" :key="factory.id" :label="factory.name"
              :value="factory.name"></el-option>
          </el-select>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>

        <div v-if="activeStep === 1">
          <el-select v-model="selectedAccount" placeholder="请选择下发账号">
            <el-option v-for="account in accountOptions" :key="account.id" :label="account.name"
              :value="account.id"></el-option>
          </el-select>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>

        <div v-if="activeStep === 2">
          <p>确认将材料下发至工厂：{{ selectedFactoryName }}</p>
          <p>工厂账号：{{ selectedAccountName }}</p>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirmSend">确认</el-button>
        </div>
      </el-dialog>

      <!-- 上传材料 -->
      <el-row :gutter="20" v-loading="loading">
        <el-col :span="12">
          <el-card shadow="never" class="upload-card">
            <template #header>
              <div class="card-header">
                <span>外箱标 </span>
                <el-button type="primary" size="small" @click="handleUpload('outerBoxLabel')">上传材料</el-button>
                <el-button type="success" size="small" @click="handleGenerate('outerBoxLabel',null,null)">在线生成</el-button>
              </div>
            </template>
            <el-collapse v-model="activeNames">
              <el-collapse-item title="查看材料" name="outerBoxLabel">
                <div v-if="form.outerBoxLabel">
                  <div v-if="isPdf(form.outerBoxLabel)">
                    <object :data="getOssUrl(form.outerBoxLabel)" type="application/pdf" width="100%" height="600px">
                      <p>无法显示PDF，请下载查看。</p>
                    </object>
                  </div>
                  <el-image v-else :src="getOssUrl(form.outerBoxLabel)" fit="contain"
                    style="width: 100%; height: 200px;"></el-image>
                  <div style="text-align: center; margin-top: 10px;">
                    <el-button type="primary" size="small" @click="downloadFile(form.outerBoxLabel)">查看</el-button>
                    <!-- 为了兼容方法第2个参数随便传个0 -->
                    <el-button type="danger" size="small" @click="handleDelete(0,0)">删除</el-button>
                  </div>
                </div>
                <div v-else class="no-file">暂无材料</div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </el-col>


    <el-col :span="12" >
          <el-card shadow="never" class="upload-card">
            <template #header>
              <div class="card-header">
                <span>产品标签 </span>
                <el-button type="success" size="small" @click="handleGenerate('productLabel',printType,null)">在线生成 </el-button>
                <!-- 打印类型单选框 -->
                 <el-radio-group v-model="printType" size="small">
                  <el-radio-button :label="0">SINGLE_COL_50_30</el-radio-button>
                  <el-radio-button :label="1">DOUBLE_COL_100_30</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <el-collapse v-model="activeNames">
              <el-collapse-item title="查看材料" name="productLabel">
                <div v-if="form.productList && form.productList.length > 0">
                  <el-collapse accordion>
                    <el-collapse-item 
                      v-for="(product, index) in form.productList" 
                      :key="index" 
                      :title="'产品: ' + product.productName + ' (' + product.fnsku + ')'"
                      :name="'product_' + index"
                    >
                <el-button type="primary" size="small" @click="handUploadProductLabel(product.id)">上传材料</el-button>
                      <div class="material-item">
                        <div v-if="product.productLabel">
                          <div v-if="isPdf(product.productLabel)">
                            <object :data="getOssUrl(product.productLabel)" type="application/pdf" width="100%" height="400px">
                              <p>无法显示PDF，请下载查看。</p>
                            </object>
                          </div>
                          <el-image v-else :src="getOssUrl(product.productLabel)" fit="contain"
                            style="width: 100%; height: 150px;"></el-image>
                          <div style="text-align: center; margin-top: 10px;">
                            <el-button type="primary" size="small" @click="downloadFile(product.productLabel)">查看</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(1,product.id)">删除</el-button>
                          </div>
                        </div>
                        <div v-else class="no-file">暂无材料</div>
                      </div>
                    </el-collapse-item>
                  </el-collapse>
                </div>
                <div v-else class="no-file">暂无产品</div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </el-col>


      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;" v-loading="loading">
        <el-col :span="12">
          <el-card shadow="never" class="upload-card">
            <template #header>
              <div class="card-header">
                <span>唛头 </span>
                <el-button type="primary" size="small" @click="handleUpload('mark')">上传材料</el-button>
                <el-button type="success" size="small" @click="handleGenerate('mark',null,markType)">在线生成</el-button>
                <!-- 打印类型单选框 -->
                <el-radio-group v-model="markType" size="small">
                  <el-radio-button :label="0">千安</el-radio-button>
                  <el-radio-button :label="1">森磊</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <el-collapse v-model="activeNames">
              <el-collapse-item title="查看材料" name="mark">
                <div v-if="form.mark">
                  <div v-if="isPdf(form.mark)">
                    <object :data="getOssUrl(form.mark)" type="application/pdf" width="100%" height="600px">
                      <p>无法显示PDF，请下载查看。</p>
                    </object>
                  </div>
                  <el-image v-else :src="getOssUrl(form.mark)" fit="contain"
                    style="width: 100%; height: 200px;"></el-image>
                  <div style="text-align: center; margin-top: 10px;">
                    <el-button type="primary" size="small" @click="downloadFile(form.mark)">查看</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(2,0)">删除</el-button>
                  </div>
                </div>
                <div v-else class="no-file">暂无材料</div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never" class="upload-card">
            <template #header>
              <div class="card-header">
                <span>印刷图 </span>
                <el-button type="primary" size="small" @click="handleUpload('printDrawings')">上传材料</el-button>
              </div>
            </template>
            <el-collapse v-model="activeNames">
              <el-collapse-item title="查看材料" name="printDrawings">
                <div v-if="form.printDrawings">
                  <div v-if="isPdf(form.printDrawings)">
                    <object :data="getOssUrl(form.printDrawings)" type="application/pdf" width="100%" height="600px">
                      <p>无法显示PDF，请下载查看。</p>
                    </object>
                  </div>
                  <el-image v-else :src="getOssUrl(form.printDrawings)" fit="contain"
                    style="width: 100%; height: 200px;"></el-image>
                  <div style="text-align: center; margin-top: 10px;">
                    <el-button type="primary" size="small" @click="downloadFile(form.printDrawings)">查看</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(3,0)">删除</el-button>
                  </div>
                </div>
                <div v-else class="no-file">暂无材料</div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </el-col>
      </el-row>

      <div style="margin-top: 20px; margin-bottom: 20px;">
        <el-button type="primary" size="small" style="float: right;"
          @click="handleConfirmAllMaterial()">一键验收</el-button>
        <div style="clear: both;"></div>
      </div>
      <!-- 产品列表 -->
      <!-- <el-button type="primary" size="small" style="float: right;" @click="handleConfirmAllMaterial()">一键验收</el-button> -->
      <el-divider content-position="left">产品列表</el-divider>
      <el-table :data="form.productList" border style="width: 100%">
        <el-table-column label="产品图片" align="center" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.image" :src="scope.row.image" :preview-src-list="[scope.row.image]"
              preview-teleported fit="cover" style="width: 50px; height: 50px" class="product-image" />
            <span v-else class="no-image">无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="productName" min-width="120" />
        <el-table-column label="FNSKU" align="center" prop="fnsku" width="120" />
        <el-table-column label="MSKU" align="center" prop="msku" width="120" />
        <el-table-column label="数量" align="center" prop="quantity" width="80" />
        <el-table-column label="箱内数量" align="center" prop="quantityinbox" width="100" />
        <el-table-column label="箱数" align="center" prop="boxNumber" width="80" />
        <el-table-column label="对应箱号" align="center" prop="boxId" width="100" />
        <el-table-column label="重量" align="center" prop="weight" width="80" />
        <el-table-column label="备注" align="center" prop="remark" min-width="100" />
        <el-table-column label="追踪编号" align="center" prop="trackingNumber" min-width="150" />
        <el-table-column label="操作" align="center" width="135">
          <template #default="scope">
            <el-button type="text" size="small" :disabled="scope.row.status == 2" @click="handleReject(scope.row)">
              驳回
            </el-button>
            <el-button type="text" size="small" :disabled="scope.row.status == 1" @click="handleConfirm(scope.row)">
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 验收材料 -->
    <el-row v-for="(material, index) in form.materialList" :key="index" :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="header-container">
              <span>验收材料 {{ index + 1 }}</span>
              <el-button type="primary" size="small" style="float: right;"
                @click="handleConfirmMaterial(material)">一键确认</el-button>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-card shadow="never" class="upload-card">
                <template #header>
                  <div class="card-header">
                    <span>外箱标/唛头</span>
                  </div>
                </template>
                <div v-if="material.outerBoxAndMarkList.length > 0">
                  <div v-for="(item, idx) in material.outerBoxAndMarkList" :key="idx" class="material-item">
                    <el-image :src="item.url" fit="contain" style="width: 15%; height: 30px;"></el-image>
                    <!-- <div style="text-align: center; margin-top: 10px;"> -->
                    <el-button type="primary" size="small" @click="downloadFile(item.url)">查看</el-button>
                    <el-button type="info" size="small" @click="loadFile(item.url)">下载</el-button>
                    <el-button type="danger" size="small" @click="handleRejectMaterial(item)"
                      :disabled="item.status === 2">驳回</el-button>
                    <el-button type="success" size="small" @click="handleConfirmMaterialItem(item)"
                      v-if="item.status != 1">确认</el-button>
                    <el-button type="success" size="small" @click="handleUnConfirmMaterialItem(item)"
                      v-if="item.status === 1" >撤销确认</el-button>
                    <!-- 显示驳回原因 -->
                    <span v-if="item.status === 2" class="reject-reason">驳回原因：{{item.cause}}</span>
                    <span v-if="item.status === 1" class="reject-reason">已确认</span>
                    <!-- </div> -->
                  </div>
                </div>
                <div v-else class="no-file">暂无材料</div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="never" class="upload-card">
                <template #header>
                  <div class="card-header">
                    <span>产品标</span>
                  </div>
                </template>
                <div v-if="material.productLabelList.length > 0">
                  <div v-for="(item, idx) in material.productLabelList" :key="idx" class="material-item">
                    <el-image :src="item.url" fit="contain" style="width: 15%; height: 30px;"></el-image>
                    <!-- <div style="text-align: center; margin-top: 10px;"> -->
                    <el-button type="primary" size="small" @click="downloadFile(item.url)">查看</el-button>
                    <el-button type="info" size="small" @click="loadFile(item.url)">下载</el-button>
                    <el-button type="danger" size="small" @click="handleRejectMaterial(item)"
                      :disabled="item.status === 2">驳回</el-button>
                    <el-button type="success" size="small" @click="handleConfirmMaterialItem(item)"
                      v-if="item.status != 1">确认</el-button>
                    <el-button type="success" size="small" @click="handleUnConfirmMaterialItem(item)"
                      v-if="item.status === 1" >撤销确认</el-button>
                    <span v-if="item.status === 2" class="reject-reason">驳回原因：{{item.cause}}</span>
                    <span v-if="item.status === 1" class="reject-reason">已确认</span>
                    <!-- </div> -->
                  </div>
                </div>
                <div v-else class="no-file">等待工厂上传</div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 文件上传对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <FileUpload :file-type="upload.fileType" :limit="1" @update:modelValue="handleUploadSuccess" :return-url="true" />
    </el-dialog>

    <!-- 驳回原因弹出框 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回原因" width="30%">
      <el-form :model="rejectReasonForm">
        <el-form-item label="驳回原因">
          <el-input v-model="rejectReasonForm.reason" type="textarea" placeholder="请输入驳回原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmRejectMaterial">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShipmentDetail" lang="ts">
import { getShipment, updateShipment, onlineGenerate, confirmOrReject, confirmOrRejectMaterial, delUploadPdf, getAccountsApi,getFactoriesApi, sendZipToFactory,uploadProductLabel } from '@/api/ymxbh/shipment';
import { ShipmentVO } from '@/api/ymxbh/shipment/types';
import FileUpload from '@/components/FileUpload/index.vue';
import { ref, reactive } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const loading = ref(true);
//下发工厂
const showDialog = ref(false);
const activeStep = ref(0);
const selectedFactory = ref(null);
const selectedAccount = ref(null);
const factoryOptions = ref([]);
const accountOptions = ref([]);
const selectedFactoryName = ref('');
const selectedAccountName = ref('');

//产品标打印类型
const printType = ref(0);
//唛头打印类型
const markType = ref(0);

// 折叠面板控制
const activeNames = ref([]);
const rejectDialogVisible = ref(false);
const rejectReasonForm = reactive({
  reason: ''
});
let currentRejectMaterialId = ref(null);

// 直接下载文件
const loadFile = async (fileName: string) => {
    try {
        const url = getOssUrl(fileName);
        // 使用 fetch 获取文件内容
        const response = await fetch(url);
        const blob = await response.blob();
        
        // 创建下载链接
        const link = document.createElement('a');
        const objectUrl = URL.createObjectURL(blob);
        link.href = objectUrl;
        
        // 获取文件名
        const fileNameWithoutPath = fileName.substring(fileName.lastIndexOf('/') + 1);
        link.download = fileNameWithoutPath;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        
        // 清理
        document.body.removeChild(link);
        URL.revokeObjectURL(objectUrl);
    } catch (error) {
        proxy?.$modal.msgError("下载失败");
        console.error("下载失败:", error);
    }
};

const handleRejectMaterial = (item: any) => {
  const materialId = item.id;

  if (!materialId) {
    proxy?.$modal.msgError("材料ID不存在");
    return;
  }

  // 设置当前驳回的材料ID
  currentRejectMaterialId.value = materialId;
  // 显示驳回原因弹出框
  rejectDialogVisible.value = true;
};

const confirmRejectMaterial = async () => {
  const materialId = currentRejectMaterialId.value;
  const reason = rejectReasonForm.reason;

  if (!reason) {
    proxy?.$modal.msgError("请填写驳回原因");
    return;
  }

  try {
    // 调用后端驳回接口，并传递驳回原因
    const response = await confirmOrRejectMaterial(materialId, 2, reason);

    if (response.code === 200) {
      proxy?.$modal.msgSuccess("驳回成功");
      // 刷新数据
      getShipmentDetail(form.value.id);
      // 关闭弹出框
      rejectDialogVisible.value = false;
      // 清空驳回原因
      rejectReasonForm.reason = '';
    } else {
      proxy?.$modal.msgError(response.msg || "驳回失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("驳回失败");
  }
};


// 获取OSS文件完整URL
const getOssUrl = (fileName: string) => {
    if (!fileName) return '';
    if (fileName.startsWith('http')) {
        return fileName;
    }
    return import.meta.env.VITE_APP_BASE_API + '/resource/oss/download/' + fileName;
};

// 判断是否为PDF文件
const isPdf = (fileName: string) => {
    return fileName.toLowerCase().endsWith('.pdf');
};

// 状态选项
const statusOptions = ref([
    { label: "待处理", value: "0" },
    { label: "待确认", value: "1" },
    { label: "审核中", value: "2" },
    { label: "已驳回", value: "3" },
    { label: "审核通过", value: "4" }
]);

const form = ref<ShipmentVO>({
    id: 0,
    shipmentConfirmationId: '',
    warehouseId: '',
    factory: '',
    shopName: '',
    materialAndNumber: '',
    trackingNumber: '',
    employeeName: '',
    firstJourney: '',
    shippingAddress: '',
    orderTime: '',
    shipmentsTime: '',
    status: 0,
    outerBoxLabel: '',
    // productLabel: '',
    mark: '',
    printDrawings: '',
    productList: [],
    materialList: [],
    remark: ''
});

// 上传参数
const upload = ref({
    title: "",
    open: false,
    fieldType: "",
    fileType: ["png", "jpg", "jpeg", "gif", "pdf", "doc", "docx", "xls", "xlsx"]
});

// 处理上传
const handleUpload = (field: string) => {
    upload.value.fieldType = field;
    upload.value.title = "上传" + getFieldName(field);
    upload.value.open = true;
};

// 上传产品标签
const handUploadProductLabel = (productId: string | number) => {
    upload.value.fieldType = 'productLabel';
    upload.value.title = "上传产品标签";
    upload.value.open = true;
    // 保存当前产品ID，以便上传成功后使用
    (upload.value as any).productId = productId;
};

// 获取字段名称
const getFieldName = (field: string) => {
    const fieldMap: Record<string, string> = {
        'outerBoxLabel': '外箱标',
        'productLabel': '产品标签',
        'mark': '唛头',
        'printDrawings': '印刷图'
    };
    return fieldMap[field] || field;
};

// 上传成功回调
// const handleUploadSuccess = (name: string) => {
//     if (name) {
//         (form.value as any)[upload.value.fieldType] = name;
//         updateShipmentData();
//         proxy?.$modal.msgSuccess("上传成功");
//         upload.value.open = false;
//     }
// };

// 上传成功回调
const handleUploadSuccess = async (name: string) => {
    if (name) {
        // 如果是产品标签上传
        if (upload.value.fieldType === 'productLabel' && (upload.value as any).productId) {
            const productId = (upload.value as any).productId;
            try {
                // 调用API上传产品标签
                const response = await uploadProductLabel(productId, name);
                if (response.code === 200) {
                    // 更新对应产品的productLabel字段
                    if (form.value.productList && Array.isArray(form.value.productList)) {
                        const product = form.value.productList.find(p => p.id === productId);
                        if (product) {
                            product.productLabel = name;
                        }
                    }
                    proxy?.$modal.msgSuccess("上传成功");
                } else {
                    proxy?.$modal.msgError(response.msg || "上传失败");
                }
            } catch (error) {
                proxy?.$modal.msgError("上传失败");
            }
        } else {
            // 其他类型文件上传
            (form.value as any)[upload.value.fieldType] = name;
            updateShipmentData();
            proxy?.$modal.msgSuccess("上传成功");
        }
        upload.value.open = false;
        // 清除productId
        delete (upload.value as any).productId;
    }
};

// 删除文件
const handleDelete = (type: number,productId: number | string ) => {
    proxy?.$modal.confirm("是否确认删除该文件？").then(() => {
        // (form.value as any)[field] = "";
       return delUploadPdf(form.value.id, type,productId);
    }).then(() => {
        // 刷新页面或更新对应字段的显示
        getShipmentDetail(form.value.id);
        proxy?.$modal.msgSuccess("删除成功");
    }).catch(() => {});
};

// 更新货件数据
const updateShipmentData = () => {
    const updateForm = { ...form.value };
    delete (updateForm as any).productList;
    return updateShipment(updateForm).then(response => {
        if (response.code === 200) {
            return response;
        } else {
            throw new Error(response.msg);
        }
    });
};

// 在线生成
const handleGenerate = async (field: string,printType: number,markType: number) => {
    loading.value = true;
    console.log(`在线生成 ${field}`);
    // 获取当前货件ID
    const id = form.value.id;
    if (!id) {
        proxy?.$modal.msgError("货件ID不存在");
        return;
    }

    // 根据字段确定type值
    let type = 0;
    switch (field) {
        case 'productLabel':
            type = 1;
            break;
        case 'outerBoxLabel':
            type = 2;
            break;
        case 'mark':
            type = 3;
            break;
        case 'printDrawings':
            type = 4;
            break;
        default:
            proxy?.$modal.msgError("不支持的生成类型");
            return;
    }

    try {
        // 调用后端在线生成接口，传递type参数
        const response = await onlineGenerate(id, type,printType,markType);

        if (response.code === 200 && response.data) {
            // 更新对应的字段值
            (form.value as any)[field] = response.data.url;

            // 更新数据库
            // await updateShipmentData();

            // 由于后端已经更新了数据库，前端只需要刷新页面显示
            proxy?.$modal.msgSuccess("在线生成成功");
            
            // 刷新页面或更新对应字段的显示
            getShipmentDetail(id);
            loading.value = false;
        } else {
            proxy?.$modal.msgError(response.msg || "在线生成失败");
        }
    } catch (error) {
        proxy?.$modal.msgError("在线生成失败");
    }
};

// 产品确认操作
const handleConfirm = async (row: any) => {
  const id = row.id;
  if (!id) {
    proxy?.$modal.msgError("产品不存在");
    return;
  }

  try {
    // 调用后端确认接口
    const response = await confirmOrReject(id, true);

    if (response.code === 200) {
      proxy?.$modal.msgSuccess("确认成功");
      // 刷新数据
      getShipmentDetail(form.value.id);
    } else {
      proxy?.$modal.msgError(response.msg || "确认失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("确认失败");
  }
};

// 驳回操作
const handleReject = async (row: any) => {
  const id = row.id;
  if (!id) {
    proxy?.$modal.msgError("产品不存在");
    return;
  }

  try {
    // 调用后端驳回接口
    const response = await confirmOrReject(id, false);

    if (response.code === 200) {
      proxy?.$modal.msgSuccess("驳回成功");
      // 刷新数据
      getShipmentDetail(form.value.id);
    } else {
      proxy?.$modal.msgError(response.msg || "驳回失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("驳回失败");
  }
};

//一键验收
const handleConfirmAllMaterial = async () => { 
  try { 
    // 存储所有需要确认的Promise
    const allConfirmPromises: Promise<any>[] = [];
    
    // 1. 确认产品列表中的每项
    if (form.value.productList && Array.isArray(form.value.productList)) {
      form.value.productList.forEach(product => {
        if (product.id) {
          allConfirmPromises.push(confirmOrReject(product.id, true));
        }
      });
    }
    
    // 2. 确认验收材料列表中的每项
    if (form.value.materialList && Array.isArray(form.value.materialList)) {
      form.value.materialList.forEach(material => {
        // 确认外箱标/唛头列表中的每项
        if (material.outerBoxAndMarkList && Array.isArray(material.outerBoxAndMarkList)) {
          material.outerBoxAndMarkList.forEach(item => {
            if (item.id) {
              allConfirmPromises.push(confirmOrRejectMaterial(item.id, 1, null));
            }
          });
        }
        
        // 确认产品标列表中的每项
        if (material.productLabelList && Array.isArray(material.productLabelList)) {
          material.productLabelList.forEach(item => {
            if (item.id) {
              allConfirmPromises.push(confirmOrRejectMaterial(item.id, 1, null));
            }
          });
        }
      });
    }
    
    // 如果没有需要确认的项目
    if (allConfirmPromises.length === 0) {
      proxy?.$modal.msgWarning("没有可确认的项目");
      return;
    }
    
    // 执行所有确认操作
    const responses = await Promise.all(allConfirmPromises);
    
    // 检查所有响应是否都成功
    const allSuccessful = responses.every(response => response.code === 200);
    
    if (allSuccessful) {
      proxy?.$modal.msgSuccess("一键验收成功");
      // 刷新数据
      getShipmentDetail(form.value.id);
    } else {
      // 如果有任何失败，找出失败的原因
      const failedResponse = responses.find(response => response.code !== 200);
      proxy?.$modal.msgError(failedResponse?.msg || "部分确认失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("一键验收失败");
  }
};

// 确认全部验收材料
const handleConfirmMaterial = async (material: any) => {
  // 从两个列表中收集所有材料项的ID
  const materialIds: any[] = [];
  
  // 收集外箱标/唛头列表中的材料ID
  if (material.outerBoxAndMarkList && Array.isArray(material.outerBoxAndMarkList)) {
    material.outerBoxAndMarkList.forEach((item: any) => {
      if (item.id) {
        materialIds.push(item.id);
      }
    });
  }
  
  // 收集产品标列表中的材料ID
  if (material.productLabelList && Array.isArray(material.productLabelList)) {
    material.productLabelList.forEach((item: any) => {
      if (item.id) {
        materialIds.push(item.id);
      }
    });
  }

  // 检查是否有材料需要确认
  if (materialIds.length === 0) {
    proxy?.$modal.msgError("没有可确认的材料");
    return;
  }

  try {
    // 创建一个确认所有材料的Promise数组
    const confirmPromises = materialIds.map(id => confirmOrRejectMaterial(id, 1, null));
    
    // 等待所有确认操作完成
    const responses = await Promise.all(confirmPromises);
    
    // 检查所有响应是否都成功
    const allSuccessful = responses.every(response => response.code === 200);
    
    if (allSuccessful) {
      proxy?.$modal.msgSuccess("全部确认成功");
      // 刷新数据
      getShipmentDetail(form.value.id);
    } else {
      // 如果有任何失败，找出失败的原因
      const failedResponse = responses.find(response => response.code !== 200);
      proxy?.$modal.msgError(failedResponse?.msg || "部分确认失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("确认失败");
  }
};

// 确认单个材料项
const handleConfirmMaterialItem = async (item: any) => {
  const materialId = item.id;

  if (!materialId) {
    proxy?.$modal.msgError("材料ID不存在");
    return;
  }

  try {
    // 调用后端确认接口
    const response = await confirmOrRejectMaterial(materialId, 1,null);

    if (response.code === 200) {
      proxy?.$modal.msgSuccess("确认成功");
      // 刷新数据
      getShipmentDetail(form.value.id);
    } else {
      proxy?.$modal.msgError(response.msg || "确认失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("确认失败");
  }
};

// 撤销确认单个材料项
const handleUnConfirmMaterialItem = async (item: any) => {
  const materialId = item.id;

  if (!materialId) {
    proxy?.$modal.msgError("材料ID不存在");
    return;
  }

  try {
    // 调用后端确认接口
    const response = await confirmOrRejectMaterial(materialId, 0,null);

    if (response.code === 200) {
      proxy?.$modal.msgSuccess("撤销成功");
      // 刷新数据
      getShipmentDetail(form.value.id);
    } else {
      proxy?.$modal.msgError(response.msg || "撤销失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("撤销失败");
  }
};

// 下载文件
const downloadFile = (fileName: string) => {
    window.open(getOssUrl(fileName), '_blank');
};

const goBack = () => {
    router.go(-1);
};

const handlePrint = () => {
    proxy?.$modal.msgSuccess("打印功能待实现");
};

const getShipmentDetail = async (id: string | number) => {
    const res = await getShipment(id);
    form.value = res.data;
};

// 获取工厂列表
const getFactories = async () => {
  try {
    const response = await getFactoriesApi();
    if (response.code === 200) {
      factoryOptions.value = response.data.map(item => ({
        id: item.roleId,
        name: item.roleName
      }));
    }
  } catch (error) {
    proxy?.$modal.msgError('获取工厂列表失败');
  }
};

// 获取工厂账号列表
const getAccounts = async (name: string) => {
  try {
    const response = await getAccountsApi(name);
    if (response.code === 200) {
      accountOptions.value = response.data.map(item => ({
        id: item.userId,
        name: item.userName
      }));
    }
  } catch (error) {
    proxy?.$modal.msgError('获取工厂账号列表失败');
  }
};

// 选择工厂后的操作
watch(selectedFactory, async (newVal) => {
  if (newVal) {
    const factory = factoryOptions.value.find(f => f.name === newVal);
    selectedFactoryName.value = factory ? factory.name : '';
    await getAccounts(newVal);
  }
});

// 选择账号后的操作
watch(selectedAccount, (newVal) => {
  if (newVal) {
    const account = accountOptions.value.find(a => a.id === newVal);
    selectedAccountName.value = account ? account.name : '';
  }
});

// 下一步操作
const nextStep = () => {
  if (activeStep.value < 2) {
    activeStep.value++;
  }
};

// 取消操作
const cancel = () => {
  showDialog.value = false;
  activeStep.value = 0;
  selectedFactory.value = null;
  selectedAccount.value = null;
  selectedFactoryName.value = '';
  selectedAccountName.value = '';
};

// 确认下发操作
const confirmSend = async () => {
  if (!selectedFactory.value || !selectedAccount.value) {
    proxy?.$modal.msgError('请选择工厂和账号');
    return;
  }
  try {
    const response = await sendZipToFactory(form.value.id, selectedAccount.value)

    if (response.code === 200) {
      proxy?.$modal.msgSuccess('下发成功');
      cancel(); // 发送成功后重置状态
    } else {
      proxy?.$modal.msgError(response.msg || '下发失败');
    }
  } catch (error) {
    proxy?.$modal.msgError('下发失败');
  }
};

onMounted(() => {
  getFactories();
    const id = route.params.id || route.query.id;
    if (id) {
        if (Array.isArray(id)) {
            getShipmentDetail(id[0]);
        } else {
            getShipmentDetail(id);
        }
    } else {
        proxy?.$modal.msgError("参数错误");
        goBack();
    }
    loading.value = false;
});
</script>

<style lang="scss" scoped>
.header-container {
    display: flex;
    align-items: center;
}

.button-group {
    margin-top: 20px;
    text-align: center;
}

.product-image {
    border-radius: 4px;
    transition: transform 0.3s ease;

    &:hover {
        transform: scale(1.1);
    }
}

.no-image {
    color: #909399;
    font-size: 12px;
}

:deep(.el-descriptions__cell) {
    padding: 8px 12px;
}

@media print {
    .button-group {
        display: none;
    }
}

.upload-card {
    .object-pdf {
        width: 100%;
        height: 600px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        overflow: hidden;

        & > object {
            width: 100%;
            height: 100%;
        }
    }
}

.material-item {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
  margin-bottom: 10px;

  &:last-child {
    border-bottom: none;
    padding-bottom: 0;
    margin-bottom: 0;
  }
}
</style>